package com.example.springsecurity.common.utils;

import com.example.springsecurity.common.config.RedisCache;
import com.example.springsecurity.common.config.SystemUserLoginDetail;
import com.example.springsecurity.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

import static com.example.springsecurity.common.constant.Constant.REDIS_LOGIN_PATH;

/**
 * @Description：用户登陆信息操作工具类
 * @Author： fengcheng
 * @Date： 2025/1/17 10:03
 */
@Slf4j
public class LoginInfoUtil {

    /**
     * @Description：删除用户登录信息
     * @Author：fengcheng
     * @Date：2025/1/17 11:11
     * @Param：redisCache
     * @ParamsType：[com.example.springsecurity.common.config.RedisCache]
     * @Return：java.lang.Boolean
     */
    public static Boolean deleteUserLoginInfo(RedisCache redisCache) {
        try {
            //获取SecurityContextHolder中的用户id
            UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
            SystemUserLoginDetail sysUser = (SystemUserLoginDetail) authentication.getPrincipal();
            String mobile = sysUser.getSystemUser().getMobile();
            // 清除SecurityContextHolder中的用户信息
            SecurityContextHolder.getContext().setAuthentication(null);
            //删除redis中的值
            redisCache.deleteObject(REDIS_LOGIN_PATH + mobile);
        } catch (Exception e) {
            log.error("删除用户登录信息发生异常，退出系统失败：{}", e.getMessage(), e);
            throw new BizException("500", "删除用户登录信息发生异常，退出系统失败");
        }
        return true;
    }
}
